﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//确认存在不同的管理器
[RequireComponent(typeof(DataManager))]
[RequireComponent(typeof(PlayerManager))]
[RequireComponent(typeof(InventoryManager))]
[RequireComponent(typeof(MissionManager))]

public class Manager : MonoBehaviour {

    //访问管理器的静态属性
    public static DataManager Data { get; private set; }
    public static PlayerManager Player { get; private set; }
    public static InventoryManager Inventory { get; private set; }
    public static MissionManager Mission { get; private set; }
    //启动时遍历的管理器列表
    private List<IGameManager> _startSequence;

    void Awake()
    {
        //对象在场景间持久化
        DontDestroyOnLoad(gameObject);

        Data = GetComponent<DataManager>();
        Player = GetComponent<PlayerManager>();
        Inventory = GetComponent<InventoryManager>();
        Mission = GetComponent<MissionManager>();

        _startSequence = new List<IGameManager>();
        _startSequence.Add(Player);
        _startSequence.Add(Inventory);
//        _startSequence.Add(Mission);
        _startSequence.Add(Data);
        //异步启动序列
        StartCoroutine(StartupManagers());
    }

    private IEnumerator StartupManagers()
    {
        NetworkService network = new NetworkService();

        foreach (IGameManager manager in _startSequence)
        {
            manager.Startup(network);
        }

        yield return null;

        int numModules = _startSequence.Count;
        int numReady = 0;
        //循环至所有管理器启动为止
        while (numReady < numModules)
        {
            int lastReady = numReady;
            numReady = 0;
            foreach (IGameManager manager in _startSequence)
            {
                if (manager.status == ManagerStatus.Started)
                {
                    numReady++;
                }
            }

            if (numReady > lastReady)
            {
                Debug.Log("Progress:" + numReady + "/" + numModules);
                //根据事件广播数据
                Messenger<int ,int>.Broadcast(StartupEvent.MANAGERS_PROGRESS,numReady,numModules);
                //再检查之前，停顿一帧
                yield return null;
            }

            Debug.Log("All managers started up");
            //Startup事件不使用参数广播
            Messenger.Broadcast(StartupEvent.MANAGERS_STARTED);
        }
    }

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}
